package cn.fisok.pdman.command.impl;

import cn.fisok.pdman.command.ExecResult;
import cn.fisok.raw.kit.JdbcKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Map;

/**
 * Ping连接数据库测试
 */
public class PingDBCommand extends AbstractDBCommand<ExecResult> {
    private Logger logger = LoggerFactory.getLogger(getClass());
    public ExecResult exec(Map<String, String> params) {
        super.init(params);
        ExecResult ret = new ExecResult();

        try {
            Class.forName(driverClassName);
            ret.setStatus(ExecResult.SUCCESS);
        } catch (ClassNotFoundException e) {
            logger.error("",e);
            ret.setStatus(ExecResult.FAILED);
            ret.setBody("驱动加载失败，驱动类不存在(ClassNotFoundException)！出错消息："+e.getMessage());
            return ret;
        }

        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url, username, password);
            ret.setStatus(ExecResult.SUCCESS);
            ret.setBody("连接成功");
        } catch (SQLException e) {
            ret.setStatus(ExecResult.FAILED);
            ret.setBody("连接失败!出错消息："+e.getMessage());
            logger.warn("",e);
        } finally {
            JdbcKit.close(conn);
        }

        return ret;
    }
}
